package com.eportal.action.background;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.action.BaseAction;
import com.eportal.domain.AppStore;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TAgent;
import com.eportal.domain.TCommunity;
import com.eportal.domain.TMirrorAgent;
import com.eportal.service.AppStoreService;
import com.eportal.service.TAgentService;
import com.eportal.service.TCommunityService;
import com.eportal.service.TMirrorAgentService;
import com.eportal.util.Config;
import com.eportal.util.HomePageConfig;
import com.eportal.util.UploadUtil;
import com.eportal.util.ValidateUtil;
import com.eportal.util.WebUtil;
import com.framework.jqgrid.JqGridPager;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 应用管理
 * @author chencheng
 *
 */
public class AppStoreAction extends BaseAction implements ModelDriven<AppStore> {
	
    /**
	 * @author chencheng
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(AppStoreAction.class.getName());

    private Map<String, Object> result = new HashMap<String, Object>();

    @Autowired
    private AppStoreService appStoreService;
    @Autowired
    private TCommunityService tCommunityService;
    @Autowired
    private TAgentService agentService;
    @Autowired
    private TMirrorAgentService tMirrorAgentService;
	/**
     * 应用管理
     */
    public String listView() {
    	String homePageConfig = HomePageConfig.YINGYONGGL;
    	String[] str = homePageConfig.split(",");
		getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
    	getSession().setAttribute("mpid", Integer.parseInt(str[0]));
    	String act = getRequest().getParameter("act");
    	if(act==null){
    		act="1";
    	}
    	getRequest().setAttribute("act", act);
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	getRequest().setAttribute("userRole", userRole);
        return SUCCESS;
    }
    
    /**
     * 应用列表
     */
    public void page() throws Exception {
        JqGridPager page = new JqGridPager();
        String agtCode = getRequest().getParameter("agtCode");
    	String appName = getRequest().getParameter("appName");
    	String type = getRequest().getParameter("type");
    	String ptime1 = getRequest().getParameter("ptime1");
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	StringBuilder where = new StringBuilder(" 1=1 ");
    	if (!StringUtils.isBlank(agtCode)) {
			where.append(" and  t.agtCode ='");
			where.append(agtCode);
			where.append("'");
    	}
    	if (!StringUtils.isBlank(appName)) {
    		where.append(" and  t.appName like '%");
    		where.append(appName);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(type)) {
    		where.append(" and  t.apptype = '");
    		where.append(type);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(ptime1)) {
    		where.append(" and TO_CHAR (t.ctime,'YYYY-MM-DD') ='");
    		where.append(ptime1);
    		where.append("'");
		}
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole == 1 || userRole == 2) {//平台级不用处理
    		
    	}else if (userRole == 3 || userRole == 4) {
    		where.append(" and t.agtCode ='");
    		where.append(user.getAgtCode());
    		where.append("'");
    	}else{
    		where.append(" and 1=2");
    	}
    	page.setWhere(where.toString());
        setPage(getRequest(), page);
        List<AppStore> appStores = appStoreService.list(page);
        jqGridQueryMap(AppStore.class, getRequest(), appStores, getResponse(), page);
    }
    
    

    /**
     * APP列表
     */
    public void list() throws Exception {
    	String sid = getRequest().getParameter("sid");
    	TCommunity tCommunity = tCommunityService.get(Long.parseLong(sid));
    	List<AppStore> appStores =null;
    	if (tCommunity == null) {
    		responseBody(appStores);
    		return;
		}
    	StringBuilder where = new StringBuilder("from AppStore where 1=1 ");
    	where.append(" and agtCode ='");
    	where.append(tCommunity.getAgtCode());
    	where.append("'");
    	appStores = appStoreService.list(where.toString());
        responseBody(appStores);
    }

    
    
    /**
     * 应用增加
     */
    public String addView() {
    	List<TMirrorAgent> list = tMirrorAgentService.listAllForWxXcx();
    	getRequest().setAttribute("xcxlist", list);
        return SUCCESS;
    }
    
    /**
     * 应用新增保存
     */
    public void add(){
		AppStore appStore = getModel();
		String msg = ValidateUtil.validate(appStore);
		result = new HashMap<String, Object>();
		if (msg == null || msg.trim().length() == 0) {
			try {
				File file = getUpload();
				String fielName = getUploadFileName();
				if (file != null) {
					result = uploadAndroidApp(file, fielName);
					if (!"1".equals(result.get("code").toString())) {
						responseBody(result);
						return;
					}
					appStore.setAndroidDownloadApp(result.get("androidDownloadApp").toString());
				}
				
				File fileLogoImg = getUpload1();
    		 	String contentLogoImg = getRequest().getParameter("contentLogoImg");
    		 	if (fileLogoImg!=null) {
    		 		result = uploadImg(fileLogoImg, contentLogoImg);
    		 		if (!"1".equals(result.get("code").toString())) {
    		 			responseBody(result);
    		 			return;
    				}
    		 		appStore.setLogoImg(WebUtil.getReqPreUrl(getRequest())+result.get("url"));
				}

				String WeChatSubscription = getRequest().getParameter("WeChatSubscription");
				String WeChatSubId = getRequest().getParameter("WeChatSubId");
				String WeChatProductId = getRequest().getParameter("WeChatProductId");
				String WeChatEncodingAESKey = getRequest().getParameter("WeChatEncodingAESKey");
				String WeChatToken = getRequest().getParameter("WeChatToken");
				result = appStoreService.addMethod(appStore, WeChatSubscription, WeChatSubId, WeChatProductId,
						WeChatEncodingAESKey, WeChatToken);
			} catch (Exception e) {
				log.error(this, e);
				result.put("code", "-1");
				result.put("msg", "应用保存失败");
			}
		} else {
			result.put("code", 0);
			result.put("msg", msg);
		}
		responseBody(result);
    }
    
    private void error(String msg) {
    	result.put("code", 0);
		result.put("msg", msg);
		responseBody(result);
	}

    /**
     * 应用修改
     */
    public String editView() {
    	try{
    		Map<String, String> appStore = appStoreService.getBySql(getModel().getSid());
            getRequest().setAttribute("appStore", appStore);
            List<TMirrorAgent> list = tMirrorAgentService.listAllForWxXcx();
        	getRequest().setAttribute("xcxlist", list);
    	}catch(Exception e){
    		log.error(this, e);
    	}
        return SUCCESS;
    }
    

    /**
     * 应用设置
     */
    public String setView() {
    	try{
    		Map<String, String> appStore = appStoreService.getBySql(getModel().getSid());
            getRequest().setAttribute("appStore", appStore);
            String downloadUrl = getDownloadUrl(getRequest(),getModel().getSid().toString());
            getRequest().setAttribute("downloadUrl", downloadUrl);
    	}catch(Exception e){
    		log.error(this, e);
    	}
        return SUCCESS;
    }
	
    /**
     * 应用设置
     */
    public void set() {
    	AppStore appStore = getModel();
    	result = new HashMap<String, Object>();
    	AppStore old = appStoreService.get(appStore.getSid());
        	try {
        		String isUseDefaultTopImg = getRequest().getParameter("isUseDefaultTopImg");
        		if("0".equals(isUseDefaultTopImg)){
        			File file = getUpload1();
        		 	String fielName =  getRequest().getParameter("content1");
        		 	if (file!=null) {
        		 		result = uploadImg(file,fielName);
        		 		if (!"1".equals(result.get("code").toString())) {
        		 			responseBody(result);
        		 			return;
        				}
        		 		old.setDownloadImg1(result.get("url").toString());
    				}
        		}else{
        			old.setDownloadImg1(null);
        		}
        		String isUseDefaultBottomImg = getRequest().getParameter("isUseDefaultBottomImg");
        		if("0".equals(isUseDefaultBottomImg)){
        			File file = getUpload2();
        		 	String fielName = getRequest().getParameter("content2");
        		 	if (file!=null) {
        		 		result = uploadImg(file,fielName);
        		 		if (!"1".equals(result.get("code").toString())) {
        		 			responseBody(result);
        		 			return;
        				}
        		 		old.setDownloadImg2(result.get("url").toString());
    				}
        		}else{
        			old.setDownloadImg2(null);
        		}
    		 	appStoreService.update(old);
   		 	 	result.put("code", 1);
    		    result.put("msg","操作成功");
        	} catch (Exception e) {
    			result.put("code", "-1");
    			result.put("msg", "应用设置失败");
    			log.error(this,e);
    		}
        responseBody(result);
    }
    
    /**
     * 关于我们
     */
    public String aboutUsView() {
    	try{
    		AppStore appStore = appStoreService.get(getModel().getSid());
            getRequest().setAttribute("appStore", appStore);
    	}catch(Exception e){
    		log.error(this, e);
    	}
        return SUCCESS;
    }
    
    public void aboutUsUpdate() {
    	try{
    		AppStore appStore = getModel();
        	result = new HashMap<String, Object>();
        	AppStore old = appStoreService.get(appStore.getSid());
        	old.setAddr(appStore.getAddr());
        	old.setIntro(appStore.getIntro());
        	old.setSiteUrl(appStore.getSiteUrl());
        	old.setTel(appStore.getTel());
        	appStoreService.update(old);
        	result.put("code", 1);
		    result.put("msg","操作成功");
    	}catch(Exception e){
    		log.error(this, e);
    		result.put("code", "-1");
			result.put("msg", "操作失败");
    	}
    	responseBody(result);
        return;
    }
    
    public String userProtocolView() {
    	try{
    		AppStore appStore = appStoreService.get(getModel().getSid());
            getRequest().setAttribute("appStore", appStore);
    	}catch(Exception e){
    		log.error(this, e);
    	}
        return SUCCESS;
    }
    
    public void userProtocolUpdate() {
    	try{
    		String homePageConfig = HomePageConfig.YINGYONGGL;
        	String[] str = homePageConfig.split(",");
    		getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
        	getSession().setAttribute("mpid", Integer.parseInt(str[0]));
    		AppStore appStore = getModel();
        	result = new HashMap<String, Object>();
        	AppStore old = appStoreService.get(appStore.getSid());
        	old.setUserProtocol(appStore.getUserProtocol());
        	appStoreService.update(old);
        	result.put("code", 1);
		    result.put("msg","操作成功");
    	}catch(Exception e){
    		log.error(this, e);
    		result.put("code", "-1");
			result.put("msg", "操作失败");
    	}
    	responseBody(result);
        return;
    }
    
    
    /**
     * 应用修改保存
     * @throws SQLException 
     * @throws SerialException 
     */
    public void update() throws SerialException, SQLException{
    	AppStore appStore = getModel();
    	appStore.setAgtCode("1");
		try {
			String msg = ValidateUtil.validate(appStore);
			result = new HashMap<String, Object>();
			if (msg == null || msg.trim().length() == 0) {

				File file = getUpload();
				String fielName = getUploadFileName();
				if (file != null) {
					result = uploadAndroidApp(file, fielName);
					if (!"1".equals(result.get("code").toString())) {
						responseBody(result);
						return;
					}
					appStore.setAndroidDownloadApp(result.get("androidDownloadApp").toString());
				}

				File fileLogoImg = getUpload1();
				String contentLogoImg = getRequest().getParameter("contentLogoImg");
				if (fileLogoImg != null) {
					result = uploadImg(fileLogoImg, contentLogoImg);
					if (!"1".equals(result.get("code").toString())) {
						responseBody(result);
						return;
					}
					appStore.setLogoImg(WebUtil.getReqPreUrl(getRequest()) + result.get("url"));
				}

				String WeChatSubscription = getRequest().getParameter("WeChatSubscription");
				String WeChatSubId = getRequest().getParameter("WeChatSubIdHidden");
				String WeChatSubIdWeb = getRequest().getParameter("WeChatSubIdWeb");
				if (StringUtils.isBlank(WeChatSubId) && StringUtils.isNotBlank(WeChatSubIdWeb)) {
					WeChatSubId = WeChatSubIdWeb;
				}
				String WeChatProductId = getRequest().getParameter("WeChatProductId");
				String WeChatEncodingAESKey = getRequest().getParameter("WeChatEncodingAESKey");
				String WeChatToken = getRequest().getParameter("WeChatToken");
				// result =
				// appStoreService.updateMethod(appStore,WeChatSubscription,WeChatSubId,WeChatProductId,WeChatEncodingAESKey,WeChatToken);
				result = appStoreService.updateMethod(appStore, WeChatSubscription, WeChatSubIdWeb, WeChatProductId,
						WeChatEncodingAESKey, WeChatToken);
			} else {
				result.put("code", 0);
				result.put("msg", msg);
				log.error("应用修改失败,参数错误");
			}
		} catch (Exception e) {
			result.put("code", "-1");
			result.put("msg", "应用修改失败");
			log.error("应用修改失败",e);
		}
        responseBody(result);
    }
    
    
    private Map<String, Object> uploadAndroidApp(File file, String fielName) {
    	result = new HashMap<String, Object>();
    	result.put("code", "-1");
    	try {
	    	if (file.length() > 51200000) {
					result.put("msg", "Andriod应用不能大于50M");
					return result;
			}
	 		
			if (StringUtils.isBlank(fielName) || !"apk".equals(FilenameUtils.getExtension(fielName))) {
				
				result.put("msg", "无法获取Andriod应用,请确认程序格式");
				return result;
			}
			String url = File.separator+"upload"+File.separator+"appStore"+File.separator;
			String destDir = ServletActionContext.getRequest().getServletContext().getRealPath(url);
	        //String destDir = ServletActionContext.getRequest().getServletContext().getRealPath(Config.APPSTORE);
	        if (!new File(destDir).exists()) {
					new File(destDir).mkdirs();
				}
	        String androidDownloadApp = System.currentTimeMillis() + "."+FilenameUtils.getExtension(fielName);
			//FileUtils.copyFile(file, new File(destDir, androidDownloadApp));
	        FileUtils.copyFile(file, new File(destDir, androidDownloadApp));
			result.put("code", "1");
			result.put("androidDownloadApp", (url+androidDownloadApp).replace(File.separator, "/"));
		} catch (IOException e) {
			log.error(this, e);
			result.put("msg", "应用上传到服务器失败，请重试");
		}
    	return result;
	}
    
    
    private Map<String, Object> uploadImg(File file, String fielName) {
    	result = new HashMap<String, Object>();
    	result.put("code", "-1");
    	try {
	    	if (file.length() > 5120000) {
				result.put("msg", "不能大于5M");
				return result;
			}
	 		String ext=",png,jpg,bmp,gif,";
			if (StringUtils.isBlank(fielName) || ext.indexOf(","+FilenameUtils.getExtension(fielName)+",")==-1) {
				result.put("msg", "请上传png,jpg,bmp,gif格式的图片");
				return result;
			}
			String url = File.separator+"upload"+File.separator+"file"+File.separator;
	        String destDir = ServletActionContext.getRequest().getServletContext().getRealPath(url);
	        if (!new File(destDir).exists()) {
				new File(destDir).mkdirs();
			}
	        String filename = UUID.randomUUID().toString().replace("-", "") + "."+FilenameUtils.getExtension(fielName);
			FileUtils.copyFile(file, new File(destDir, filename));
			result.put("code", "1");
			result.put("url", (url+filename).replace(File.separator, "/"));
		} catch (IOException e) {
			log.error(this, e);
			result.put("msg", "上传传到服务器失败，请重试");
		}
    	return result;
	}

	/**
     * 社区审核后选择关联APP
     * @return
     */
    public String selectApp(){
    	String sid = getRequest().getParameter("sid");
    	getRequest().setAttribute("sid", sid);
    	 return SUCCESS;
    }
    /**
     * APP下载页
     * @return
     */
    public String downloadAppView(){
    	String sid = getRequest().getParameter("sid");
    	if(sid==null){//考虑到生成二维码的复杂度，尽量减小参数名的长度
    		sid= getRequest().getParameter("i");
    	}
    	AppStore appStore=  appStoreService.get(Long.parseLong(sid));
    	if (appStore == null) {
    		return "error";
		}
    	getRequest().setAttribute("sid", sid);
    	getRequest().setAttribute("name", appStore.getAppName());
    	getRequest().setAttribute("iosAppDownload", appStore.getIosUpdateUrl());
    	getRequest().setAttribute("wxzUrl", appStore.getWxzUrl());
    	TAgent agent = agentService.get(appStore.getAgtCode());
    	
    	String bannerImgUrl = null;
    	if(appStore.getDownloadImg1()!=null){
    		bannerImgUrl = WebUtil.getReqPreUrl(getRequest())+appStore.getDownloadImg1();
    		getRequest().setAttribute("bannerImgUrl",bannerImgUrl);
    	}else{
    		if(agent!=null&&"1".endsWith(agent.getType())){//判断合作方类型，锁厂和社区显示的默认banner图不一样
        		getRequest().setAttribute("bannerImgUrl", WebUtil.getReqPreUrl(getRequest())+"/static/images/admin/appstore/lock_banner.png");
        	}else{
        		getRequest().setAttribute("bannerImgUrl",WebUtil.getReqPreUrl(getRequest())+"/static/images/admin/appstore/wuye_banner.png");
        	}
    	}
    	String bottomUrl = null;
    	if(appStore.getDownloadImg2()!=null){
    		bottomUrl = WebUtil.getReqPreUrl(getRequest())+appStore.getDownloadImg2();
    		getRequest().setAttribute("bottomImgUrl",bottomUrl);
    	}else{
    		getRequest().setAttribute("bottomImgUrl",WebUtil.getReqPreUrl(getRequest())+"/static/images/admin/appstore/lock_bottom.png");
    	}
    	
    	if(appStore.getAndroidDownloadApp()==null){//判断是否上传了安卓app
    		getRequest().setAttribute("androidId","");
    		getRequest().setAttribute("androidUrl","");
    	}else{
    		getRequest().setAttribute("androidId",appStore.getSid());
    		String destDir = ServletActionContext.getRequest().getServletContext().getRealPath("/");
    		getRequest().setAttribute("androidUrl",WebUtil.getReqPreUrl(getRequest())+appStore.getAndroidDownloadApp());
    		
    	}
    	return SUCCESS;
    }
    /**
     * 安卓APP下载
     * @return
     */
    public void downloadApp(){
    	try {
    		String sid = getRequest().getParameter("sid");
        	AppStore appStore=  appStoreService.get(Long.parseLong(sid));
        	if (appStore == null) {
        		return;
    		}
    		String destDir = ServletActionContext.getRequest().getServletContext().getRealPath("/");
    		UploadUtil.download(destDir,appStore.getAndroidDownloadApp(),getResponse());
		} catch (Exception e) {
			 log.error(this, e);
		}
    }
    
    /**
     * 下载二维码图片
     * @return
     */
	public void downloadQrcode() {
		try {
			String sid = getRequest().getParameter("sid");
			String downloadUrl = getDownloadUrl(getRequest(),sid);
			String format = "jpg";
			// 设置二维码的参数
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 编码
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);// 容错率
			hints.put(EncodeHintType.MARGIN, 0);
			try {
				// 生成二维码
				BitMatrix bitMatrix = new MultiFormatWriter().encode(downloadUrl, BarcodeFormat.QR_CODE, 430, 430,
						hints);
				// 输出图片
				BufferedImage image = toBufferedImage(bitMatrix);
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				ImageIO.write(image, format, out);
				HttpServletResponse response = getResponse();
				response.reset();
				// 设置response的Header
				// response.setContentType("application/vnd.ms-excel");
				response.setContentType("application/octet-stream");
				response.addHeader("Content-Disposition",
						"attachment;filename=" + java.net.URLEncoder.encode("app_qrcode." + format, "UTF-8"));
				// response.addHeader("Content-Length", "" + file.length());
				OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
				toClient.write(out.toByteArray());
				toClient.flush();
				toClient.close();
			} catch (Exception e) {
				log.error(this, e);
			}
		} catch (Exception e) {
			log.error(this, e);
		}
	}
   
	public static BufferedImage toBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}
	
	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;
    
    private File upload1;
    private File upload2;
    
	/**
	 * 应用的下载地址
	 * @param req
	 * @param sid
	 * @return
	 */
	private String getDownloadUrl(HttpServletRequest req,String sid){
		String downloadUrl = WebUtil.getReqPreUrl(getRequest()) + "u/b?i=" + sid;
		return downloadUrl;
	}
   
    private AppStore appStore = new AppStore();

    
    @Override
    public AppStore getModel() {
        return appStore;
    }

	public File getUpload1() {
		return upload1;
	}

	public void setUpload1(File upload1) {
		this.upload1 = upload1;
	}

	public File getUpload2() {
		return upload2;
	}

	public void setUpload2(File upload2) {
		this.upload2 = upload2;
	}
    
    
}
